import { getUser, verifyToken } from "@/lib/authUtils";
import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/index.mjs";
import { match } from "ts-pattern";
import { NextRequest, NextResponse } from 'next/server';
import prisma from "@/lib/prisma";
import { checkUserLimit, incrementUserCount } from '@/lib/limitChecker'

export async function POST(request: NextRequest) {
  try {
    const token = request.headers.get('authorization')?.replace('Bearer ', '') ||
                  request.cookies.get('token')?.value
    
    if (!token) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }

    const decoded = await verifyToken(token)
    if (!decoded) {
      return NextResponse.json({ error: '无效的令牌' }, { status: 401 })
    }

    // 检查使用限制
    const limitCheck = await checkUserLimit(decoded.userId, 'ai_count')
    if (!limitCheck.allowed) {
      return NextResponse.json({ 
        error: 'AI生成次数已达上限',
        currentCount: limitCheck.currentCount,
        limit: limitCheck.limit,
        planType: limitCheck.planType
      }, { status: 429 })
    }

    const userid = await getUser(request)
    if (!userid || userid instanceof NextResponse) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_BASE_URL,
    });
    // Check if the OPENAI_API_KEY is set, if not return 400
    if (!process.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY === "") {
      return new Response("Missing OPENAI_API_KEY - make sure to add it to your .env file.", {
        status: 400,
      });
    }

    const { prompt, option, command } = await request.json();

    const BASE_ROLE = "你是youtube视频博主，拥有百万粉丝账号操盘经验.";
    const COMMON_REQUIREMENTS = 
      "◆ 始终使用口语化表达\n" +
      "◆ 采用「悬念前置+信息密度」结构\n" +
      "◆ 每15秒设置一个剧情钩子\n";

    const messages = match(option)
    .with("generate", () => [
      {
        role: "system",
        content:BASE_ROLE+
        "根据现有内容写一篇完整的文案\n" +
        "▼ 核心要求\n" +
        "● 首行必须生成3个爆款标题选项（emoji+数字标题）\n" +
        "● 后半段优先安排转化触发点\n" +
        "● 结尾预留互动话术接口\n" 
      },
      {
        role: "user",
        content: prompt,
      },
    ])
    .with("improve", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
        "根据输入的文稿进行文本润色，要求文本正式，内容精简严肃，抓住用户痛点吸引用户观看，只返回处理后的文稿。"
      },
      {
        role: "user",
        content: `现有文本是：${prompt}`,
      },
    ])
    .with("shorter", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
       "根据输入的文稿进行高质量文本摘要，只返回处理后内容。"
      },
      {
        role: "user",
        content: `现有文本是：${prompt}`,
      },
    ])
    .with("longer", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
        "根据输入的文稿进行文本续写，要求文本正式，内容精简严肃，只返回续写的内容。"
      },
      {
        role: "user",
        content: `现有文本是：${prompt}`,
      },
    ])
    .with("fix", () => [
      {
        role: "system",
        content:
        BASE_ROLE + "润色文案,修复语法和拼写错误，返回需要修改语法和拼写的点，无需返回完整文本\n" 
      },
      {
        role: "user",
        content: `现有文本是：${prompt}`,
      },
    ])
    .with("zap", () => [
      {
        role: "system",
        content:
        BASE_ROLE +
          "根据输入的文稿和要求进行文本修改" +
          "在适当的时候使用Markdown格式。",
      },
      {
        role: "user",
        content: `对于这段文本：${prompt}。你必须遵守这些要求：${command}`,
      },
    ])
    .run() as ChatCompletionMessageParam[];

    const response = await openai.chat.completions.create({
      model: "deepseek-chat",
      stream: true,
      temperature: 1.2,
      messages,
    });

    // Create a ReadableStream from the OpenAI response
    const stream = new ReadableStream({
      async start(controller) {
        const encoder = new TextEncoder();
        
        for await (const chunk of response) {
          const content = chunk.choices[0]?.delta?.content || "";
          controller.enqueue(encoder.encode(content));
        }
        controller.close();
      },
    });

    // 增加使用次数
    await incrementUserCount(decoded.userId, 'ai_count')
    
    // Return the stream with proper headers
    return new Response(stream, {
      headers: {
        'Content-Type': 'text/plain; charset=utf-8',
        'Transfer-Encoding': 'chunked',
      },
    });
    
  } catch (error) {
    console.error('AI生成失败:', error)
    return NextResponse.json(
      { error: 'AI生成失败' }, 
      { status: 500 }
    )
  }
}
